package com.qing.demo.netty.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;

/**
 * @author caozhipeng
 * @date 2025/7/25
 */
public class MyInMsgHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel socketChannel=(SocketChannel)ctx.channel();
        System.out.println("客户端链接报告开始！");
        System.out.println("客户端链接报告信息：本客户端链接到服务器。ChannelID="+socketChannel.id());
        System.out.println("客户端链接报告结束！");

        String msg = "通知服务端，客户端链接建立成功！";
        ctx.writeAndFlush(msg);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ctx.writeAndFlush("客户端发送随机数："+Math.random()*10+"\r\n");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端通道关闭");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("异常信息："+cause.getMessage());
    }
}
